import * as vscode from 'vscode'
import { PanelProvider } from '@/views/panel/backend/panel-provider'
import { dictionary } from '@shared/constants/dictionary'
import { DeleteSeparatorMessage } from '@/views/panel/types/messages'
import { ConfigPresetFormat } from '@/views/panel/backend/utils/preset-format-converters'

export const handle_delete_separator = async (
  panel_provider: PanelProvider,
  message: DeleteSeparatorMessage,
  webview_view: vscode.WebviewView
): Promise<void> => {
  const separator_index = message.index
  const config = vscode.workspace.getConfiguration('codeWebChat')
  const presets_config_key = panel_provider.get_presets_config_key()
  const current_presets =
    config.get<ConfigPresetFormat[]>(presets_config_key, []) || []

  if (separator_index < 0 || separator_index >= current_presets.length) return

  const updated_presets = [...current_presets]
  updated_presets.splice(separator_index, 1)

  try {
    await config.update(
      presets_config_key,
      updated_presets,
      vscode.ConfigurationTarget.Global
    )

    panel_provider.send_presets_to_webview(webview_view.webview)
  } catch (error) {
    vscode.window.showErrorMessage(
      dictionary.error_message.FAILED_TO_DELETE_ITEM('separator', error)
    )
  }
}
